package com.tiny.core.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.tiny.core.common.LoggerUtils;
import com.tiny.core.dao.LoginfoDao;
import com.tiny.core.domain.Loginfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoggerInterceptor implements HandlerInterceptor {

    private final static Logger logger = LoggerFactory.getLogger(LoggerInterceptor.class);

    private static final String LOGGER_SEND_TIME = "_send_time";
    private static final String LOGGER_ENTITY = "_logger_entity";
     
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        logger.info("--preHandle  start--");

        Loginfo loginfo = new Loginfo();
        String sessionId = request.getRequestedSessionId();
        String url = request.getRequestURI();
        String paramData = JSON.toJSONString(request.getParameterMap(),
                SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteMapNullValue);


        loginfo.setRequestClientIp(LoggerUtils.getCliectIp(request));
        loginfo.setRequestMethod(request.getMethod());
        loginfo.setRequestType(LoggerUtils.getRequestType(request));
        loginfo.setRequestParamData(paramData);
        loginfo.setRequestUri(url);
        loginfo.setRequestSessionId(sessionId);

        request.setAttribute(LOGGER_SEND_TIME,System.currentTimeMillis());
        request.setAttribute(LOGGER_ENTITY,loginfo);
        logger.info("--preHandle  end--");
        return true;
    }


    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        logger.info("--postHandle  start--");

    }


    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {
        logger.info("--afterCompletion  start--");
        int status = response.getStatus();
        long currentTime = System.currentTimeMillis();
        long time = Long.valueOf(request.getAttribute(LOGGER_SEND_TIME).toString());
        Loginfo loginfo = (Loginfo) request.getAttribute(LOGGER_ENTITY);
        loginfo.setRequestTimeConsuming(Integer.valueOf((currentTime - time)+""));
        loginfo.setRequestReturnTime(currentTime + "");
        loginfo.setRequestHttpStatusCode(status + "");
        loginfo.setRequestReturnData(JSON.toJSONString(request.getAttribute(LoggerUtils.LOGGER_RETURN),
                SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteMapNullValue));

        LoginfoDao loginfoDao = getDAO(LoginfoDao.class,request);
        loginfoDao.add(loginfo);
        logger.info("--afterCompletion  end--");

    }
    /**
     * 根据传入的类型获取spring管理的对应dao
     * @param clazz 类型
     * @param request 请求对象
     * @param <T>
     * @return
     */
    private <T> T getDAO(Class<T> clazz,HttpServletRequest request) {
        BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
        return factory.getBean(clazz);
    }

}
